<template>
  <div class="stuff-container flex-x gap-3">
    <!--  左侧树  -->
    <el-card style="max-width: 220px;">
      <!--  搜索  -->
      <div slot="header">
        <div class="flex-x gap-2 pt-2">
          <span style="width: 120px;">
            <vxe-input v-model="query.keyword" style="width: 120px;" :placeholder="'搜索目录名称'" size="medium"
                       clearable
                       @keyup.enter.native="loadData"></vxe-input>
          </span>
          <span class="flex-1"></span>
          <span>
            <el-button type="primary" size="small" @click="handleAddDir" icon="el-icon-plus"/>
          </span>
        </div>
      </div>

      <!-- 树 -->
      <div class="flex-y px--6 mx--4" style="min-height: 50vh;">
        <el-tree ref="treeRef" :data="dirList" :props="dirTreeProps" node-key="id" :indent="8" :expand-on-click-node="false"
                 :highlight-current="true" :default-expanded-keys="[0]" :default-checked-keys="[0]"
                 @node-click="handleNodeClick">
          <template #default="{ node, data }">
            <div class="flex-x justify-between items-center gap-2 w-full py-1">
              <i v-if="data.stuffType==='dir'" :class="['fa', node.expanded ? 'fa-folder-open' : 'fa-folder']"/>
              <i v-else class="fa fa-file-o"/>
              <span>{{ data.title }}</span>
              <div class="flex-1 flex-x justify-end mr-2">
                <div class="hover-actions ml-2" v-if="data.stuffType==='dir'">
                  <el-button type="text" size="mini" @click.stop="handleEditDir(data)">
                    <i class="el-icon-edit"></i>
                  </el-button>
                  <el-button type="text" size="mini" @click.stop="handleDeleteDir(data)">
                    <i class="el-icon-delete"></i>
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </el-tree>
      </div>
    </el-card>

    <!--  右侧内容区  -->
    <div v-if="currStuff.stuffType==='dir'" class="flex-1">
      <StuffTable :parent-id="currStuff.id"/>
    </div>

    <!-- Dir Dialog -->
    <el-dialog :title="dirDialogTitle" :visible.sync="dirDialogVisible" width="480px" @close="resetDirForm"
               destroy-on-close>
      <el-form :model="dirForm" :rules="rules" ref="dirForm" label-width="100px">

        <el-form-item label="上级目录" prop="parentId">
          <stuff-dir-select v-model="dirForm.parentId"></stuff-dir-select>
        </el-form-item>

        <el-form-item label="目录名称" prop="title">
          <el-input v-model="dirForm.title"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dirDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDirForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import StuffTable from './StuffTable.vue'
import api from "@/common/api.js";
import utils from "@/common/utils.js";
import StuffDirSelect from "@/components/admin/StuffDirSelect.vue";

export default {
  name: 'CourseStuff',
  components: {
    StuffDirSelect,
    StuffTable
  },
  props: {},
  data() {
    return {
      loading: false,

      query: {
        keyword: ''
      },
      dirTreeProps: {
        label: 'title',
        children: 'children',
        isLeaf: (data) => {
          return data.stuffType !== 'dir'
        }
      },
      dirList: [],
      currStuff: {},

      dirProps: {
        label: 'title',
        children: 'children',
        isLeaf: 'leaf'
      },

      dirDialogVisible: false,
      dirDialogTitle: '',
      dirForm: {
        title: '',
        stuffType: 'dir'
      },
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
        ],
        stuffType: [
          {required: true, message: '请输入类型', trigger: 'blur'}
        ],
        fileUrl: [
          {required: true, message: '请上传文件', trigger: 'change'}
        ]
      }
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      try {
        this.loading = true;
        const {data} = await api.admin_getStuffList({limit: 1000});
        const dirList = data.data.records;
        const rootDir = {
          id: 0,
          stuffType: 'dir',
          title: '所有素材',          
        }

        // 排序，目录在前，文件在后，然后按id倒序
        dirList.sort((a, b) => {
          if (a.stuffType === 'dir' && b.stuffType !== 'dir') return -1;
          if (a.stuffType !== 'dir' && b.stuffType === 'dir') return 1;
          return b.id - a.id;
        });

        this.dirList = utils.buildTreeWithParentId(dirList, rootDir);

        // 初始化 currStuff
        if (!this.currStuff.stuffType) {          
          this.currStuff = rootDir;
          this.$nextTick(() => {
            this.$refs.treeRef.setCurrentKey(this.currStuff.id)
          })
        }
      } finally {
        this.loading = false;
      }
    },
    handleNodeClick(data) {
      console.log('handleNodeClick', data);
      this.currStuff = data;
    },

    handleAddDir() {
      this.dirDialogTitle = '添加目录';
      this.dirDialogVisible = true;
      this.dirForm = {
        id: null,
        parentId: this.currStuff.id,
        title: ''
      };
    },
    handleEditDir(node) {
      this.dirDialogTitle = '编辑目录';
      this.dirDialogVisible = true;
      const parentId = node.parentId || 0;
      this.dirForm = Object.assign({}, node, {parentId});
    },
    handleDeleteDir(node) {
      this.$confirm('此操作将永久删除该目录及其下的所有素材, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true;
          await api.admin_deleteStuff(node.id);
          this.$message.success('删除成功');
          await this.loadData();
        } finally {
          this.loading = false;
        }
      })
    },
    resetDirForm() {
      this.dirForm = {
        id: null,
        title: ''
      };
    },
    submitDirForm() {
      this.$refs.dirForm.validate(async (valid) => {
        if (!valid) return;
        try {
          this.loading = true;
          const data = Object.assign({}, this.dirForm, {stuffType: 'dir'})
          await api.admin_saveStuff(data);
          this.$message.success('操作成功');

          this.dirDialogVisible = false;
          await this.loadData();
        } finally {
          this.loading = false;
        }
      });
    },

    beforeFileUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!isLt100M) {
        this.$message.error('文件大小不能超过 100MB!');
        return false;
      }
      return true;
    }
  }
}
</script>

<style scoped>
.stuff-container {
  :deep(.el-tree-node__content) {
    height: 36px;
    line-height: 36px;
  }

  :deep(.el-tree-node__content:hover .hover-actions) {
    opacity: 1;
  }

  .hover-actions {
    opacity: 0;
  }
}


</style>
